package com.wtf.service;

import com.wtf.dao.UserTokenDao;
import com.wtf.pojo.UserToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;
import java.util.UUID;

/**
 * @author tengfei wang
 * @version 1.0
 * @date Created in 2020/11/2
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Resource
    private UserTokenDao userTokenDao;

    @Resource
    private CodeFeignService codeFeignService;

    @Override
    public boolean register(String email, String password, Integer code, HttpServletResponse response) {
        // 校验邮箱注册状态
        if (isRegister(email)) {
            log.error("邮箱 {} 已注册", email);
            return false;
        }

        // 校验code是否正确
        Integer num = codeFeignService.validCode(email, code);
        if (num != 0) {
            log.error("code={} 校验未通过, 原因 {}", code, num);
            return false;
        }

        UserToken userToken = new UserToken();
        userToken.setEmail(email);
        userToken.setPassword(password);
        String token = UUID.randomUUID().toString();
        userToken.setToken(token);
        userTokenDao.save(userToken);
        // 将token写入cookie
        Cookie cookie = new Cookie("token", UUID.randomUUID().toString());
        response.addCookie(cookie);

        return true;
    }

    @Override
    public boolean isRegister(String email) {
        UserToken userToken = new UserToken();
        userToken.setEmail(email);
        Example<? extends UserToken> ex = Example.of(userToken);
        Optional<? extends UserToken> optional = userTokenDao.findOne(ex);
        // 校验邮箱是否已经注册过，如果注册过，返回true
        if (optional.isPresent()) {
            log.error("邮箱 {} 已经注册", email);
            return true;
        }
        return false;
    }

    @Override
    public String login(String email, String password, HttpServletResponse response) {
        UserToken user = new UserToken();
        user.setEmail(email);
        user.setPassword(password);
        Example<UserToken> example = Example.of(user);
        Optional<UserToken> optional = userTokenDao.findOne(example);
        if (!optional.isPresent()) {
            log.error("用户名或密码错误");
            return null;
        }
        Cookie cookie = new Cookie("token", UUID.randomUUID().toString());
        response.addCookie(cookie);

        return email;
    }

    @Override
    public String getEmailByToken(String token) {
        UserToken userToken = new UserToken();
        userToken.setToken(token);
        Example<? extends UserToken> ex = Example.of(userToken);
        Optional<? extends UserToken> optional = userTokenDao.findOne(ex);
        return optional.map(UserToken::getEmail).orElse(null);
    }
}
